package com.justgame.project.cloud.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 获取Application上下文
 *
 * @author zhouweibo
 */
@Component("appContextUtils")
public class AppContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    public static <T> Collection<T> getBeans(Class<T> beanClass) {
        return applicationContext.getBeansOfType(beanClass).values();
    }

    public static boolean containsBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }

    public static Class<?> getType(String beanName) {
        return applicationContext.getType(beanName);
    }

    public static ApplicationContext getContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        AppContextUtils.applicationContext = applicationContext;
    }
}
